<template>
	<view class="container">
		<view class="login-card">
			<view class="login-logo">
				<image src="/static/logo.png" mode="aspectFit"></image>
			</view>
			<view class="login-title">欢迎使用粉红日记</view>
			<view class="login-subtitle">记录健康，关爱自己</view>

			<!-- 头像选择区域 -->
			<view class="login-avatar-container">
				<image class="preview-avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
				<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					选择头像
				</button>
			</view>

			<!-- 昵称输入区域 -->
			<view class="nickname-container">
				<view class="nickname-label">您的昵称</view>
				<input 
					type="nickname" 
					class="nickname-input"
					placeholder="请输入昵称" 
					:value="userInfo.nickName"
					@change="onInputNickname"
				/>
			</view>

			<!-- 登录按钮 -->
			<view class="login-button-container">
				<button class="wechat-login-btn" @tap="handleLogin">
					<view class="wechat-icon">
						<!-- <image src="/static/wechat-icon.png"> </image> -->
					</view>
					<text>微信一键登录</text>
				</button>
			</view>
			
			<view class="login-tips">登录即表示同意《用户协议》和《隐私政策》</view>
		</view>
		
		<!-- 提示组件 -->
		<wd-toast ref="toast"></wd-toast>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

// 用户信息
const userInfo = reactive({
	nickName: '粉红日记_用户',
	avatar: '/static/default-avatar.png'
})

// Toast引用
const toast = ref(null)

// 页面初始化
onMounted(() => {
	// 检查是否已经登录
	checkLoginStatus()
})

// 检查登录状态，避免重复登录
const checkLoginStatus = () => {
	const isLogin = uni.getStorageSync('isLogin')
	if (isLogin === 'true') {
		// 已登录，直接跳转到首页
		uni.switchTab({
			url: '/pages/home/home'
		})
	}
}

// 选择头像回调
const onChooseAvatar = (e) => {
	userInfo.avatar = e.detail.avatarUrl
}

// 输入昵称回调
const onInputNickname = (e) => {
	userInfo.nickName = e.detail.value
}

// 显示提示
const showToast = (message) => {
	uni.showToast({
		title: message,
		icon: 'none',
		duration: 2000
	})
}

// 处理登录逻辑
const handleLogin = async () => {
	try {
		// 表单验证
		if (!userInfo.avatar || userInfo.avatar === '/static/default-avatar.png') {
			return showToast('请选择您的头像')
		}
		
		if (!userInfo.nickName || userInfo.nickName.trim() === '') {
			return showToast('请输入您的昵称')
		}
		
		// 显示加载
		uni.showLoading({
			title: '登录中...'
		})
		
		// 获取微信登录凭证（code）
		const { code } = await getWxCode()
		
		// 调用云函数进行登录
		const result = await loginWithWeChat(code)
		
		if (result.code === 0) {
			// 登录成功，保存用户信息
			saveUserInfo(result.data)
			
			// 显示登录成功提示
			uni.hideLoading()
			showToast('登录成功')
			
			// 延迟跳转，让用户看到提示
			setTimeout(() => {
				// 跳转到首页
				uni.switchTab({
					url: '/pages/home/home'
				})
			}, 1500)
		} else {
			uni.hideLoading()
			showToast(result.message || '登录失败，请重试')
		}
	} catch (error) {
		console.error('登录失败', error)
		uni.hideLoading()
		showToast('登录失败，请重试：' + (error.message || '未知错误'))
	}
}

// 获取微信登录code
const getWxCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				if (res.code) {
					resolve({ code: res.code })
				} else {
					reject(new Error('获取微信登录凭证失败'))
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 调用云函数进行登录
const loginWithWeChat = async (code) => {
	try {
		const { result } = await uniCloud.callFunction({
			name: 'wx-login',
			data: {
				code,
				userInfo: {
					nickName: userInfo.nickName,
					avatarUrl: userInfo.avatar
				}
			}
		})
		
		return result
	} catch (error) {
		console.error('调用云函数失败', error)
		throw error
	}
}

// 保存用户信息到本地存储
const saveUserInfo = (data) => {
	// 保存登录状态
	uni.setStorageSync('isLogin', 'true')
	
	// 保存用户ID
	uni.setStorageSync('userId', data.userId)
	
	// 保存token
	uni.setStorageSync('token', data.token)
	
	// 保存openid
	uni.setStorageSync('openid', data.openid)
	
	// 保存完整用户信息
	const userData = {
		userId: data.userId,
		openid: data.openid,
		nickName: userInfo.nickName,
		avatar: userInfo.avatar,
		cycleCount: data.cycle_count || 0
	}
	
	uni.setStorageSync('userInfo', JSON.stringify(userData))
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40rpx;
	background-color: $background-color;
}

.login-card {
	width: 100%;
	background: $background-color;
	border-radius: 20rpx;
	padding: 40rpx;
	box-shadow: 0 8rpx 16rpx rgba(255, 105, 180, 0.1);
	display: flex;
	flex-direction: column;
	align-items: center;
}

.login-logo {
	width: 180rpx;
	height: 180rpx;
	margin-bottom: 30rpx;
}

.login-logo image {
	width: 100%;
	height: 100%;
}

.login-title {
	font-size: 40rpx;
	font-weight: bold;
	color: $brand-theme-color;
	margin-bottom: 16rpx;
}

.login-subtitle {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 60rpx;
}

.login-avatar-container {
	width: 150rpx;
	height: 150rpx;
	position: relative;
	margin-bottom: 40rpx;
}

.preview-avatar {
	width: 150rpx;
	height: 150rpx;
	border-radius: 75rpx;
	border: 2px solid $brand-theme-color;
}

.avatar-btn {
	position: absolute;
	bottom: -20rpx;
	right: -20rpx;
	background: $brand-theme-color;
	color: white;
	font-size: 22rpx;
	border-radius: 30rpx;
	padding: 6rpx 16rpx;
	line-height: 1.5;
	border: none;
}

.nickname-container {
	width: 100%;
	margin-bottom: 60rpx;
}

.nickname-label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 16rpx;
}

.nickname-input {
	width: 100%;
	height: 80rpx;
	background: #F8F8F8;
	border-radius: 40rpx;
	padding: 0 30rpx;
	font-size: 28rpx;
}

.login-button-container {
	width: 100%;
	margin-bottom: 30rpx;
}

.wechat-login-btn {
	width: 100%;
	height: 90rpx;
	background: #3BAF34;
	color: white;
	border-radius: 45rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	border: none;
}

.wechat-icon {
	width: 50rpx;
	height: 50rpx;
	margin-right: 16rpx;
}

.wechat-icon image {
	width: 100%;
	height: 100%;
}

.login-tips {
	font-size: 24rpx;
	color: #999;
	text-align: center;
}
</style> 